package com.ptszyxx.popose.module.chat.page;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import androidx.lifecycle.ViewModelProviders;
import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.constants.BundleConstant;
import com.ptszyxx.popose.common.enums.EditEnum;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ptszyxx.popose.common.utils.YVipUtil;
import com.ptszyxx.popose.common.utils.sensitive.YSensitiveUtil;
import com.tencent.qcloud.tuikit.tuichat.zhiyu.callback.ExpressionMessageCallback;
import com.ysg.enums.NoDiamondEnum;
import com.ysg.utils.YCollectionUtil;
import com.ysg.utils.YPermissionUtil;
import com.ysg.utils.YUserUtil;
import com.ptszyxx.popose.databinding.FragmentChatBinding;
import com.ysg.enums.ChatCallEnum;
import com.ptszyxx.popose.module.chat.page.vm.ChatVM;
import com.tencent.qcloud.tuicore.TUILogin;
import com.tencent.qcloud.tuicore.util.ToastUtil;
import com.tencent.qcloud.tuikit.timcommon.bean.TUIMessageBean;
import com.tencent.qcloud.tuikit.timcommon.interfaces.OnItemClickListener;
import com.tencent.qcloud.tuikit.tuichat.bean.ChatInfo;
import com.tencent.qcloud.tuikit.tuichat.classicui.widget.input.InputView;
import com.tencent.qcloud.tuikit.tuichat.presenter.C2CChatPresenter;
import com.tencent.qcloud.tuikit.tuichat.zhiyu.callback.BooleanCallback;
import com.tencent.qcloud.tuikit.tuichat.zhiyu.callback.CustomMessageCallback;
import com.tencent.qcloud.tuikit.tuichat.zhiyu.callback.IInputCallback;
import com.tencent.qcloud.tuikit.tuichat.zhiyu.widget.UserInfoView;
import com.ysg.base.BaseActivity;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.http.data.entity.im.ChatBlackEntity;
import com.ysg.http.data.entity.user.UserResult;
import com.ysg.utils.YDialogUtil;
import com.ysg.utils.YImageUtil;
import com.ysg.utils.YSPUtils;
import com.ysg.utils.YStatusBarUtil;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;
import com.ysg.widget.dialog.CallDialog;
import com.ysg.widget.dialog.ExpressionDialog;
import com.ysg.widget.dialog.GiftDialog;
import com.ysg.widget.dialog.IntimacyGiftDialog;
import com.ysg.widget.dialog.VideoAudioPriceDialog;
import com.ysg.widget.dialog.entity.GiftListResult;
import com.ysg.widget.dialog.entity.GiftNumResult;
import com.ysg.widget.title.YTitleBar;

/**
 * 参考：tuichat模块下的TUIC2CChatActivity
 */
public class ChatFragment extends BaseActivity<FragmentChatBinding, ChatVM> implements IInputCallback {
    private ChatInfo chatInfo;
    private C2CChatPresenter presenter;
    private YTitleBar titleBar;
    private CustomMessageCallback customMessageCallback;
    private ExpressionMessageCallback expressionMessageCallback;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.fragment_chat;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public ChatVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(ChatVM.class);
    }

    @Override
    public void initStatusBar() {
        super.initStatusBar();
        YStatusBarUtil.setColorTheme(this, titleBar, com.ysg.R.color.transparent);
        YStatusBarUtil.setImageTheme(this, titleBar);
    }

    @Override
    public void initParam() {
        super.initParam();
        if (!TUILogin.isUserLogined()) {
            ToastUtil.toastShortMessage(getString(com.tencent.qcloud.tuikit.tuichat.R.string.chat_tips_not_login));
            finish();
            return;
        }
        Intent bundle = getIntent();
        if (bundle != null){
            viewModel.txUserId = bundle.getStringExtra(BundleConstant.CHAT_USER_ID);
            viewModel.userName = bundle.getStringExtra(BundleConstant.CHAT_USER_NAME);//TODO 通知栏昵称有错（自己的）
            viewModel.userPic = bundle.getStringExtra(BundleConstant.CHAT_USER_PIC);
        }

        chatInfo = new ChatInfo();
        chatInfo.setType(ChatInfo.TYPE_C2C);
        chatInfo.setId(viewModel.txUserId);
        chatInfo.setChatName(viewModel.userName);
        chatInfo.setFaceUrl(viewModel.userPic);
        chatInfo.setTopChat(false);

        if (chatInfo == null) {
            ToastUtil.toastShortMessage("聊天初始化失败，chatInfo为空");
            finish();
        }
    }

    @Override
    public void initView() {
        super.initView();
        presenter = new C2CChatPresenter();
        presenter.initListener();

        binding.chatView.initDefault(null);
        binding.chatView.setPresenter(presenter);
        presenter.setChatInfo(chatInfo);
        presenter.setTypingListener(binding.chatView.mTypingListener);
        binding.chatView.setChatInfo(chatInfo);

        InputView inputLayout = binding.chatView.getInputLayout();
        inputLayout.setOnInputCallback(this);
        initTitleBar();
        initImageBg();
        initUserInfoView();
        onItemClickListener();
        onReceiveGiftListener();
    }

    @Override
    public void initData() {
        super.initData();
        if (!YStringUtil.isAdmin(viewModel.txUserId)){
            viewModel.requestUser();
            viewModel.requestIsBlack(null, viewModel.txUserId);
        }
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onUserInfoEvent.observe(this, o -> setUserInfoUI((UserResult) o));
        viewModel.uc.onClearMessageEvent.observe(this, o -> presenter.clearMessage());
        viewModel.baseUC.onGiftDialogEvent.observe(this, o -> showDialogGift(customMessageCallback));
        viewModel.baseUC.onCallDialogEvent.observe(this, o -> showDialogCall());
        viewModel.baseUC.onCallPriceEvent.observe(this, o -> showDialogAudioVideoPrice());
        viewModel.baseUC.onNoDiamondEvent.observe(this, o -> showDialogNoDiamond(NoDiamondEnum.text));
        viewModel.baseUC.onNoDiamondGiftEvent.observe(this, o -> showDialogNoDiamond(NoDiamondEnum.gift));
        viewModel.baseUC.onNoDiamondCallEvent.observe(this, o -> showDialogNoDiamond(NoDiamondEnum.call));
        viewModel.baseUC.onIntimacyEvent.observe(this, o -> showDialogIntimacyGift((String) o));
        viewModel.uc.onExpressionDialogEvent.observe(this, o -> showDialogExpression(this.expressionMessageCallback));
    }

    /**
     * 接收到礼物：播放礼物动画
     */
    private void onReceiveGiftListener() {
        presenter.setOnReceiveGiftListener((gifUrl)-> showDialogSvga(gifUrl));
    }

    /**
     * 列表点击事件
     */
    public void onItemClickListener(){
        binding.chatView.getMessageLayout().setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onMessageClick(View view, int position, TUIMessageBean messageBean) {
            }

            @Override
            public void onMessageLongClick(View view, int position, TUIMessageBean message) {
                binding.chatView.getMessageLayout().showItemPopMenu(position - 1, message, view);
            }

            @Override
            public void onUserIconClick(View view, int position, TUIMessageBean message) {
                if (!YStringUtil.isAdmin(message.getV2TIMMessage().getSender())){
                    YActivityUtil.getInstance().jumpUserDetail(viewModel, message.getV2TIMMessage().getSender());
                }
            }

            @Override
            public void onReEditRevokeMessage(View view, int position, TUIMessageBean messageInfo) {
            }

            @Override
            public void onRecallClick(View view, int position, TUIMessageBean messageInfo) {
            }

            @Override
            public void onTextSelected(View view, int position, TUIMessageBean messageInfo) {
            }

            @Override
            public void onMessageReadStatusClick(View view, TUIMessageBean messageBean) {
            }
        });
    }

    /**
     * 标题栏
     */
    public void initTitleBar(){
        titleBar = binding.chatView.getYTitleBar();
        titleBar.setTitle(viewModel.userName);
        if (YStringUtil.isAdmin(viewModel.txUserId)){
            titleBar.setRightVisible(false);
        }
        titleBar.setOnTitleBarListener(new YTitleBar.OnTitleBarListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onTitleClick() {
            }

            @Override
            public void onRightClick() {
                YActivityUtil.getInstance().jumpChatSet(viewModel, viewModel.txUserId, viewModel.userName, viewModel.userPic);
            }
        });
    }

    /**
     * 图片背景
     */
    private ImageView ivBg;
    public void initImageBg(){
        ivBg = binding.chatView.getImageBg();
        if(YStringUtil.isNotEmpty(viewModel.userPic)){
            YImageUtil.showBlur(ivBg, viewModel.userPic);
        }
    }

    /**
     * 列表头部的用户信息
     */
    private UserInfoView userInfoCardView;
    public void initUserInfoView(){
        userInfoCardView = binding.chatView.getUserInfoView();
        userInfoCardView.setOnUserInfoListener(()->{
            YActivityUtil.getInstance().jumpUserDetail(viewModel, viewModel.txUserId);
        });
        if (YStringUtil.isAdmin(viewModel.txUserId)){
            userInfoCardView.setVisibility(View.GONE);
        }
        userInfoCardView.setOnUserInfoListener(()->YActivityUtil.getInstance().jumpUserDetail(viewModel, viewModel.txUserId));
    }
    /**
     * 列表头部的用户信息
     */
    public void setUserInfoUI(UserResult user){
        titleBar.setTitle(viewModel.userName);
        userInfoCardView.setData(user);
    }


    /**
     * 消息发送前处理
     */
    @Override
    public void beforeSend(String input, BooleanCallback callback){
        if (!check()){
            return;
        }
        YPermissionUtil.requestStorage(this, "申请存储权限：用于下载敏感词文件。", new YPermissionUtil.OnPermissionListener() {
            @Override
            public void onSuccess() {
                //检测敏感词
                String sensitiveData = YSensitiveUtil.checkSensitiveContent(input);
                if (YStringUtil.isNotEmpty(sensitiveData)){
                    showDialogSensitive();
                    viewModel.saveSensitive(input, sensitiveData);
                    return;
                }

                if (YStringUtil.eq(1, viewModel.blackEntity.getFree()) || YUserUtil.isVip() || YUserUtil.isGirl()){
                    if(callback != null) callback.onSuccess();
                }else{
                    viewModel.requestTextFee(input, callback, null);
                }
            }

            @Override
            public void onError() {
            }
        });
    }

    /**
     * 消息发送礼物
     */
    @Override
    public void sendGift(CustomMessageCallback callback) {
        if (!check()){
            return;
        }
        this.customMessageCallback = callback;
        viewModel.onGiftClick();
    }

    /**
     * 拨打电话
     */
    @Override
    public void onCall(CustomMessageCallback callback) {
        this.customMessageCallback = callback;
        if (!check()){
            return;
        }
        viewModel.onCallClick(viewModel.txUserId, null);
    }

    @Override
    public void onExpression(ExpressionMessageCallback callback) {
        if (!check()){
            return;
        }
        this.expressionMessageCallback = callback;
        showDialogExpression(callback);
    }

    public void showDialogExpression(ExpressionMessageCallback callback) {
        if (YCollectionUtil.isEmpty(viewModel.expressionList)){
            viewModel.requestExpression(true);
        }else{
            YDialogUtil.getInstance().showExpression(this, viewModel.expressionList)
                    .setOnClickListener(new ExpressionDialog.OnClickListener() {
                        @Override
                        public void onSendExpression(String text) {
                            viewModel.requestTextFee(text, null, callback);
                        }

                        @Override
                        public void onJumpExpression() {
                            YActivityUtil.getInstance().jumpUserEditName(viewModel, viewModel.txUserId, "", EditEnum.expression);
                        }

                        @Override
                        public void onExpressionDelete(String id) {
                            viewModel.requestExpressionDelete(id);
                        }
                    });
        }
    }

    private boolean check(){
        ChatBlackEntity blackEntity = viewModel.blackEntity;
        if (blackEntity == null){
            YToastUtil.showLong("blackEntity为空");
            return false;
        }
        if (viewModel.userEntity == null){
            YToastUtil.showLong("用户信息为空");
            return false;
        }
        if (YStringUtil.eq(1, blackEntity.getIsBlack())){
            YToastUtil.showLong(R.string.tip_black);
            return false;
        }
        return true;
    }

    /**
     * 没有钻石
     */
    private void showDialogNoDiamond(NoDiamondEnum noDiamondEnum) {
        YDialogUtil.getInstance().showNoDiamond(this, noDiamondEnum, YVipUtil.isChatVipConfig());
    }

    /**
     * 礼物
     */
    private void showDialogGift(CustomMessageCallback callback){
        YDialogUtil.getInstance().showGift(ChatFragment.this, viewModel.giftListEntity, viewModel.giftNumResult)
                .setOnGiftListener(new GiftDialog.OnGiftListener() {
                    @Override
                    public void onRechargeClick() {
                        YActivityUtil.getInstance().jumpMineRecharge(viewModel);
                    }

                    @Override
                    public void onSendClick(GiftListResult.GiftBean giftBean, GiftNumResult.Data giftNumEntity) {
                        viewModel.requestSendGift(giftBean, giftNumEntity, viewModel.txUserId, callback, (url)-> showDialogSvga(url));
                    }
                });
    }

    /**
     * 礼物SVGA
     */
    private void showDialogSvga(String url){
       YDialogUtil.getInstance().showSVGA(ChatFragment.this, url);
    }

    /**
     * 通话:语音，视频
     */
    private void showDialogCall(){
        YDialogUtil.getInstance().showCall(ChatFragment.this).setOnCallListener(new CallDialog.OnCallListener() {
            @Override
            public void onAudioClick() {
                viewModel.requestVideoAudioIsEnough(ChatCallEnum.AUDIO);
            }

            @Override
            public void onVideoClick() {
                viewModel.requestVideoAudioIsEnough(ChatCallEnum.VIDEO);
            }
        });
    }

    /**
     * 通话价格
     */
    private void showDialogAudioVideoPrice(){
        YDialogUtil.getInstance().showAudioVideoPrice(ChatFragment.this, viewModel.userPic, viewModel.userEntity.getVoicePrice(), viewModel.userEntity.getVideoPrice())
                .setOnPriceListener(new VideoAudioPriceDialog.OnPriceListener() {
                    @Override
                    public void onVideoClick() {
                        YSPUtils.getInstance().saveShowVideoAudioPrice(viewModel.txUserId, true);
                        viewModel.requestIsBlack(ChatCallEnum.VIDEO, viewModel.txUserId);
                    }

                    @Override
                    public void onAudioClick() {
                        YSPUtils.getInstance().saveShowVideoAudioPrice(viewModel.txUserId, true);
                        viewModel.requestIsBlack(ChatCallEnum.AUDIO, viewModel.txUserId);
                    }
                });
    }

    /**
     * 亲密度礼物
     */
    private void showDialogIntimacyGift(String intimacyValue) {
        YDialogUtil.getInstance().showIntimacyGift(ChatFragment.this, intimacyValue)
                .setOnIntimacyGiftListener(new IntimacyGiftDialog.OnIntimacyGiftListener() {
                    @Override
                    public void onGiftClick() {
                        viewModel.onGiftClick();
                    }
                });
    }

    /**
     * 敏感词
     */
    private void showDialogSensitive(){
        YDialogUtil.getInstance().showConfirm(this, getResources().getString(R.string.dialog_sensitive_content));
    }

}
